<?php

require("db_connect.php");

function get_entity_records_xml($entity){
	$result = get_entity_records($entity);
	$obj = getEntity($entity);
	$params = $obj->get_params();
	
	while($row = mysql_fetch_assoc($result)){
		$xml .= "<entity id='".$obj->get_id()."' table='".$obj->get_table()."' display='".$obj->get_display()."'>";
			for($i=0; $i<sizeof($params); $i++){ 
				$xml .= "<param id='".$params[$i]->get_id()."' type='".$params[$i]->get_type()."' length='".$params[$i]->get_length()."' ctype='".$params[$i]->get_ctype()."' display='".$params[$i]->get_display()."' field='".$params[$i]->get_field()."' listing='".$params[$i]->get_listing()."'>";
					$xml .= $row[$params[$i]->get_field()];
				$xml .= "</param>";
			}
		$xml .= "</entity>";
	}
	return $xml;
}

function get_entity_records_obj($entity){
	$result = get_entity_records($entity);
	$objList = array();
	while($row = mysql_fetch_assoc($result)){
		$obj = getEntity($entity);
		
		$params = $obj->get_params();
		foreach($params as $param){
			$param->set_value($row[$param->get_field()]);
		}
		
		array_push($objList, $obj);
	}
	return $objList;
}

function get_entity_records($entity){
	$obj = get_entity_obj($entity);
	$params = $obj->get_params();
	
	$tablename = $obj->get_table();
	$fields = get_entity_listing_fields($entity);
	
	$sql = "select ".$fields." from ".$tablename." where 1=1 ";
	foreach($params as $param){
		if($_GET[$param->get_field()]){
			$sql .= "and ".$param->get_field()." = '".$_GET[$param->get_field()]."' ";
		}
	}
	
	$result = mysql_query($sql) or die("error getting records from database");
	
	return $result;
}

function get_entity_obj($entity){
	return getEntity($entity);
}

function get_entity_listing_fields($entity){
	$fields = "";
	$fieldList = get_entity_listing_fields_list($entity);
	for($i=0; $i<sizeof($fieldList); $i++){
		$fields .= $fieldList[$i];
		if($i < sizeof($fieldList) - 1){
			$fields .= ",";
		}
	}

	return $fields;		
}

function get_entity_listing_fields_list($entity){
	$fieldList = array();
	$obj = get_entity_obj($entity);
	$paramList = $obj->get_params();
	for($i=0; $i<sizeof($paramList); $i++){
		if($paramList[$i]->get_attribute('listing')){
			array_push($fieldList, $paramList[$i]->get_attribute('field'));
		}
	}
	
	return $fieldList;
}

?>